package com.xuan.system.controller;


import com.xuan.common.core.constants.Constants;
import com.xuan.common.core.controller.BaseController;
import com.xuan.common.core.domain.R;
import com.xuan.common.core.domain.TableDataInfo;
import com.xuan.common.core.exception.BusinessException;
import com.xuan.system.domain.question.dto.QuestionAddDTO;
import com.xuan.system.domain.question.dto.QuestionEditDTO;
import com.xuan.system.domain.question.dto.QuestionQueryDTO;
import com.xuan.system.domain.question.vo.QuestionDetailVo;
import com.xuan.system.service.question.QuestionService;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/question")
public class QuestionController extends BaseController {

    @Autowired
    private QuestionService questionService;

    @GetMapping("/list")
    public TableDataInfo listQuestion(QuestionQueryDTO questionQueryDTO) {
        String excludeIdStr = questionQueryDTO.getExcludeIdStr();
        // 解析竞赛信息中, 用户已经选择的题目 id
        if (StringUtils.isNotBlank(excludeIdStr)) {
            String[] excludeIdArr = excludeIdStr.split(Constants.SPLIT_SEM);
            Set<Long> excludeIdSet = Arrays.stream(excludeIdArr).map(Long::parseLong).collect(Collectors.toSet());
            questionQueryDTO.setExcludeIdSet(excludeIdSet);
        }
        return questionService.listQuestion(questionQueryDTO);
    }

    @PostMapping("/add")
    public R<Void> addQuestion(@RequestBody QuestionAddDTO questionAddDto) {
        if (questionAddDto == null) {
            throw new BusinessException("参数为空");
        }
        return toR(questionService.addQuestion(questionAddDto));
    }

    @DeleteMapping("/delete")
    public R<Void> deleteQuestion(Long questionId) {
        if (questionId == null) {
            throw new BusinessException("参数为空");
        }
        return toR(questionService.deleteQuestion(questionId));
    }

    @PutMapping("/edit")
    public R<Void> editQuestion(@RequestBody QuestionEditDTO questionEditDto) {
        if (questionEditDto == null) {
            throw new BusinessException("参数为空");
        }
        return toR(questionService.editQuestion(questionEditDto));
    }

    @GetMapping("/detail")
    public R<QuestionDetailVo> getQuestionDetail(Long questionId) {
        if (questionId == null) {
            throw new BusinessException("参数为空");
        }
        return R.ok(questionService.getQuestionDetail(questionId));
    }
}
